<template>
  <div class="app-main">
    <my-header title="GoodsList案例"></my-header>
    <my-table :list="list">
      <template #header>
        <tr>
          <th>#</th>
          <th>商品名称</th>
          <th>价格</th>
          <th>标签</th>
          <th>操作</th>
        </tr>
      </template>
      <template #body="scope">
        <td>{{ scope.row.id }}</td>
        <td>{{ scope.row.goods_name }}</td>
        <td>{{ scope.row.goods_price }}</td>
        <td> 
            <input
            @blur="scope.row.inputVisible = false, scope.row.inputValue = ''"
            @keydown.enter="enterDown(scope.row)"
            @keydown.esc="scope.row.inputValue = ''"
            v-model="scope.row.inputValue"
            v-foc
            v-if="scope.row.inputVisible"
            class="tag-input form-control"
            style="width: 100px"
            type="text">
            <button 
            @click="isShow(scope.row)"
            v-else
            class="btn btn-primary"
            >+Tab</button>
            <br>

            <span 
            v-for="(item, index) in scope.row.tags" 
            :key="index"
            class="badge bg-warning text-dark"
            style="margin-left: 10px"
            >{{ item }}</span>
        </td>
        <td>
          <button @click="del(scope.row.id)" class="btn btn-danger">删除</button>
        </td>
      </template>
    </my-table>
  </div>
</template>

<script>
// 目标1: 渲染数据
// 目标2: 使用插槽
// 目标3: 渲染标签
// 目标4: 删除数据
// 目标5: 添加tab
import MyHeader from "../components/MyHeader.vue";
import MyTable from "../components/MyTable.vue";

export default {
  components: {
    MyHeader,
    MyTable,
  },
  data() {
    return {
      list: [],
    };
  },
  async created() {
    let res = await this.$http({
      url: "/api/goods",
    });
    // console.log(res);
    this.list = res.data.data;
  },
  methods: {
      del(id) {
        let index = this.list.findIndex(item => item.id == id)
        this.list.splice(index, 1)
      },
      isShow(row) {
        row.inputVisible = true
      },
      enterDown(row) {
          if(row.inputValue.trim() == ''){
              return alert('内容不能为空')
          }
          row.tags.push(row.inputValue)
          row.inputVisible = false
          row.inputValue = ''
      }
  },
  directives: {
      foc: {
          inserted(el){
              el.focus()
          }
      }
  }
};
</script>

<style>
.app-main {
  padding-top: 45px;
}
</style>